import React, { useState, useEffect, useCallback, useRef } from "react";
import { Button, message, Modal, Table, Space, Input, Form, InputNumber, Tree, Empty, Spin, DatePicker } from "antd";
import { PlusOutlined, DeleteOutlined, EditOutlined, FolderAddOutlined } from "@ant-design/icons";
import { v4 as uuidv4 } from "uuid";
import request from "../../utils/request";
import {
  getGISDataAreaFileList,
  getGISDataAreaTree,
  saveGISDataAreaTree,
  createGISDataAreaFile,
  deleteGISDataAreaFile,
  updateGISDataAreaFile,
  createGISDataAreaFileAll,
  GISDataAreaTreeItem,
  GISDataAreaFileItem,
  GISDataAreaFileListParams,
} from "../../api/gis";
import AddDataPickerModal from "./AddDataPickerModal";
import DataAreaBatchUploadModal from "./DataAreaBatchUploadModal";
import "./DataAreaManagement.css";

const { RangePicker } = DatePicker;

interface DataAreaManagementProps {
  planetId: number;
}

interface TreeNode {
  title: string;
  key: string;
  children?: TreeNode[];
  isLeaf?: boolean;
}

const DataAreaManagement: React.FC<DataAreaManagementProps> = ({ planetId }) => {
  // 空间数据管理相关状态
  const [dataAreas, setDataAreas] = useState<GISDataAreaFileItem[]>([]);
  const [dataAreaLoading, setDataAreaLoading] = useState(false);
  const [dataAreaModalVisible, setDataAreaModalVisible] = useState(false);
  const [editingDataArea, setEditingDataArea] = useState<GISDataAreaFileItem | null>(null);
  const [selectedDataAreaKeys, setSelectedDataAreaKeys] = useState<React.Key[]>([]);
  const [batchDeleteLoading, setBatchDeleteLoading] = useState(false);
  const [dataAreaForm] = Form.useForm();
  const [dataAreaFilterForm] = Form.useForm();


  // 添加数据相关状态
  const [addDataModalVisible, setAddDataModalVisible] = useState(false);

  // 编辑节点名称相关状态
  const [editNodeModalVisible, setEditNodeModalVisible] = useState(false);
  const [editingNode, setEditingNode] = useState<TreeNode | null>(null);
  const [editNodeForm] = Form.useForm();
  const [addingToParentKey, setAddingToParentKey] = useState<string | null>(null); // 记录添加数据集时的父任务key

  // 树形结构相关状态
  const [treeData, setTreeData] = useState<TreeNode[]>([]);
  const [treeLoading, setTreeLoading] = useState(false);
  const [selectedTreeKey, setSelectedTreeKey] = useState<string | null>(null);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [, setTreeUuid] = useState<string>("");
  const [showDataContent, setShowDataContent] = useState(false);

  // 分页状态
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(0);

  // 导入弹窗
  const [importVisible, setImportVisible] = useState(false);

  // 表格容器ref和滚动高度
  const tableContainerRef = useRef<HTMLDivElement>(null);
  const [tableScrollY, setTableScrollY] = useState(0);

  // 获取数据区域列表
  const fetchDataAreas = useCallback(async (page = 1, size = 20, filters = {}) => {
    setDataAreaLoading(true);
    try {
      const formValues = dataAreaFilterForm.getFieldsValue();

      // 如果没有选中树节点，不请求数据
      if (!selectedTreeKey) {
        setDataAreas([]);
        setTotal(0);
        setDataAreaLoading(false);
        return;
      }

      // 处理时间范围
      let createTimeGte = "";
      let createTimeLte = "";
      if (formValues.create_time_range && formValues.create_time_range.length === 2) {
        createTimeGte = formValues.create_time_range[0]?.format("YYYY-MM-DD HH:mm:ss") || "";
        createTimeLte = formValues.create_time_range[1]?.format("YYYY-MM-DD HH:mm:ss") || "";
      }

      const params: GISDataAreaFileListParams = {
        planet_id: planetId,
        tree_uuid: selectedTreeKey,
        page,
        page_size: size,
        file_name: formValues.file_name || "",
        dm_zhname: formValues.dm_zhname || "",
        data_level: formValues.data_level || "",
        create_time__gte: createTimeGte,
        create_time__lte: createTimeLte,
        ...filters,
      };

      const response = await getGISDataAreaFileList(params);

      if (response.code === 200) {
        setDataAreas(response.data.list);
        setTotal(response.data.count);
        setCurrent(response.data.page);
        setPageSize(response.data.page_size);
      } else {
        message.error(response.msg || "获取数据区域列表失败");
      }
    } catch (error) {
      console.error("获取数据区域列表失败:", error);
      message.error((error as Error)?.message || "获取数据区域列表失败");
    } finally {
      setDataAreaLoading(false);
    }
  }, [selectedTreeKey, planetId]);

  // 获取树形数据
  const fetchTreeData = async () => {
    setTreeLoading(true);
    try {
      const response = await getGISDataAreaTree({ planet_id: planetId });
      if (response.code === 200) {
        // 转换API数据为Tree组件需要的格式
        const transformTreeData = (items: GISDataAreaTreeItem[]): TreeNode[] => {
          return items.map((item) => ({
            title: item.task_name,
            key: item.task_name,
            // 用于样式控制第一级
            className: "level-1-node",
            children: item.data_set_list.map((dataSet) => ({
              title: dataSet.data_set_name,
              key: dataSet.key,
              isLeaf: true,
              // 用于样式控制第二级
              className: "level-2-node",
            })),
          }));
        };

        const newTreeData = transformTreeData(response.data);
        setTreeData(newTreeData);

        // 展开所有节点
        const getAllKeys = (nodes: TreeNode[]): string[] => {
          return nodes.reduce((keys: string[], node) => {
            keys.push(node.key);
            if (node.children) {
              keys.push(...getAllKeys(node.children));
            }
            return keys;
          }, []);
        };
        setExpandedKeys(getAllKeys(newTreeData));
      } else {
        message.error(response.msg || "获取树形数据失败");
      }
    } catch (error) {
      console.error("获取树形数据失败:", error);
      message.error((error as Error)?.message || "获取树形数据失败");
    } finally {
      setTreeLoading(false);
    }
  };

  // 导出数据集文件
  const handleExport = () => {
    if (!selectedTreeKey) {
      message.warning("请先选择数据集");
      return;
    }
    const url = (request as any).getUrl(`/GIS/GISDataAreaFileExport?planet_id=${planetId}&tree_uuid=${selectedTreeKey}`);
    console.log(url);
    window.open(url, "_blank");
  };

  // 保存树形数据
  const saveTreeData = async (
    newTreeData: TreeNode[],
    actionType: "create" | "update" | "delete" = "update",
    treeUuid?: string
  ) => {
    try {
      // 转换Tree组件数据为API需要的格式
      const transformToApiFormat = (nodes: TreeNode[]): GISDataAreaTreeItem[] => {
        return nodes.map((node) => ({
          task_name: node.title,
          data_set_list:
            node.children?.map((child) => ({
              data_set_name: child.title,
              key: child.key,
            })) || [],
        }));
      };

      const response = await saveGISDataAreaTree({
        planet_id: planetId,
        action_type: actionType,
        tree_uuid: treeUuid,
        tree: transformToApiFormat(newTreeData),
      });

      if (response.code === 200) {
        message.success("保存成功");
        // 重新获取树数据
        fetchTreeData();
      } else {
        message.error(response.msg || "保存失败");
      }
    } catch (error) {
      console.error("保存树形数据失败:", error);
      message.error((error as Error)?.message || "保存失败");
    }
  };

  // 添加任务
  const handleAddTask = () => {
    const newKey = uuidv4();
    const newTask: TreeNode = {
      title: "",
      key: newKey,
      children: [],
    };

    // 弹出编辑弹窗让用户输入名称，不立即添加到树中
    setEditingNode(newTask);
    editNodeForm.setFieldsValue({
      title: "",
    });
    setEditNodeModalVisible(true);
  };

  // 添加数据集
  const handleAddDataSet = (taskKey: string) => {
    const newKey = uuidv4();
    const newDataSet: TreeNode = {
      title: "",
      key: newKey,
      isLeaf: true,
    };

    // 记录父任务key，用于后续添加到正确的父节点下
    setAddingToParentKey(taskKey);
    
    // 弹出编辑弹窗让用户输入名称，不立即添加到树中
    setEditingNode(newDataSet);
    editNodeForm.setFieldsValue({
      title: "",
    });
    setEditNodeModalVisible(true);
  };

  // 编辑节点名称
  const handleEditNode = (node: TreeNode) => {
    setEditingNode(node);
    editNodeForm.setFieldsValue({
      title: node.title,
    });
    setEditNodeModalVisible(true);
  };

  // 保存节点名称编辑
  const handleSaveNodeEdit = async () => {
    try {
      const values = await editNodeForm.validateFields();
      if (!editingNode) return;

      // 判断是新建还是编辑：如果title为空字符串，说明是新建
      const isNewNode = editingNode.title === "";
      let newTreeData: TreeNode[];

      if (isNewNode) {
        // 新建节点：添加到树中
        const newNode = {
          ...editingNode,
          title: values.title,
        };

        if (addingToParentKey) {
          // 添加数据集到指定任务下
          const updateTreeData = (nodes: TreeNode[]): TreeNode[] => {
            return nodes.map((node) => {
              if (node.key === addingToParentKey) {
                return {
                  ...node,
                  children: [...(node.children || []), newNode],
                };
              }
              if (node.children) {
                return {
                  ...node,
                  children: updateTreeData(node.children),
                };
              }
              return node;
            });
          };
          newTreeData = updateTreeData(treeData);
        } else {
          // 添加新任务
          newTreeData = [...treeData, newNode];
        }
      } else {
        // 编辑现有节点
        const updateNodeInTree = (nodes: TreeNode[]): TreeNode[] => {
          return nodes.map((node) => {
            if (node.key === editingNode.key) {
              return {
                ...node,
                title: values.title,
              };
            }
            if (node.children) {
              return {
                ...node,
                children: updateNodeInTree(node.children),
              };
            }
            return node;
          });
        };
        newTreeData = updateNodeInTree(treeData);
      }

      setTreeData(newTreeData);
      
      const actionType = isNewNode ? "create" : "update";
      const treeUuid = isNewNode ? editingNode.key : undefined;
      
      saveTreeData(newTreeData, actionType, treeUuid);
      setEditNodeModalVisible(false);
      setEditingNode(null);
      setAddingToParentKey(null);
      editNodeForm.resetFields();
    } catch (error) {
      console.error("保存节点名称失败:", error);
    }
  };

  // 删除节点
  const handleDeleteNode = (key: string) => {
    Modal.confirm({
      title: "确认删除",
      content: "确定要删除该节点吗？删除后无法恢复。",
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        const deleteNodeFromTree = (nodes: TreeNode[]): TreeNode[] => {
          return nodes.filter((node) => {
            if (node.key === key) {
              return false;
            }
            if (node.children) {
              node.children = deleteNodeFromTree(node.children);
            }
            return true;
          });
        };

        const newTreeData = deleteNodeFromTree(treeData);
        setTreeData(newTreeData);
        saveTreeData(newTreeData, "delete", key);

        // 如果删除的是当前选中的节点，清空选择
        if (selectedTreeKey === key) {
          setSelectedTreeKey(null);
          setTreeUuid("");
          setShowDataContent(false);
        }
      },
    });
  };

  // 组件加载时获取数据
  useEffect(() => {
    fetchTreeData();
  }, [planetId]);

  // 当选择的树节点变化时，重新加载文件列表
  useEffect(() => {
    if (selectedTreeKey) {
      fetchDataAreas(1, pageSize);
    }
  }, [selectedTreeKey]);

  // 筛选表单提交
  const onDataAreaFilterFinish = () => {
    setCurrent(1);
    fetchDataAreas(1, pageSize);
  };

  // 分页处理
  const handleDataAreaTableChange = (paginationInfo: any) => {
    setCurrent(paginationInfo.current);
    setPageSize(paginationInfo.pageSize);
    fetchDataAreas(paginationInfo.current, paginationInfo.pageSize);
  };


  // 编辑数据区域（坐标和区域名称）
  const handleEditDataArea = (record: GISDataAreaFileItem) => {
    setEditingDataArea(record);
    dataAreaForm.setFieldsValue({
      area_name: record.area_name || '', // 设置区域名称，如果没有则设为空字符串
      left_latitude: record.left_latitude,
      left_longitude: record.left_longitude,
      right_latitude: record.right_latitude,
      right_longitude: record.right_longitude,
    });
    setDataAreaModalVisible(true);
  };

  // 删除数据区域文件
  const handleDeleteDataArea = async (record: GISDataAreaFileItem) => {
    if (!selectedTreeKey) {
      message.error("请先选择数据集");
      return;
    }

    Modal.confirm({
      title: "确认删除",
      content: `确定要删除文件 "${record.file_name}" 吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        try {
          const response = await deleteGISDataAreaFile({
            tree_uuid: selectedTreeKey,
            file_ids: [record.id]
          });
          if (response.code === 200) {
            message.success("删除成功");
            fetchDataAreas(current, pageSize);
          } else {
            message.error(response.msg || "删除失败");
          }
        } catch (error) {
          console.error("删除数据区域文件失败:", error);
          message.error((error as Error)?.message || "删除失败");
        }
      },
    });
  };

  // 批量删除数据区域文件
  const handleBatchDeleteDataArea = () => {
    if (selectedDataAreaKeys.length === 0) {
      message.warning("请选择要删除的文件");
      return;
    }

    if (!selectedTreeKey) {
      message.error("请先选择数据集");
      return;
    }

    Modal.confirm({
      title: "确认批量删除",
      content: `确定要删除选中的 ${selectedDataAreaKeys.length} 个文件吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        setBatchDeleteLoading(true);
        try {
          const response = await deleteGISDataAreaFile({
            tree_uuid: selectedTreeKey,
            file_ids: selectedDataAreaKeys.map((id) => Number(id))
          });
          if (response.code === 200) {
            message.success("批量删除成功");
            setSelectedDataAreaKeys([]);
            fetchDataAreas(current, pageSize);
          } else {
            message.error(response.msg || "批量删除失败");
          }
        } catch (error) {
          console.error("批量删除失败:", error);
          message.error((error as Error)?.message || "批量删除失败");
        } finally {
          setBatchDeleteLoading(false);
        }
      },
    });
  };

  // 保存数据区域（坐标和区域名称）
  const handleSaveDataArea = async () => {
    try {
      const values = await dataAreaForm.validateFields();

      if (editingDataArea) {
        const response = await updateGISDataAreaFile({
          id: editingDataArea.id,
          area_name: values.area_name,
          left_latitude: values.left_latitude,
          left_longitude: values.left_longitude,
          right_latitude: values.right_latitude,
          right_longitude: values.right_longitude,
        });
        if (response.code === 200) {
          message.success("修改成功");
          setDataAreaModalVisible(false);
          fetchDataAreas(current, pageSize);
        } else {
          message.error(response.msg || "修改失败");
        }
      }
    } catch (error) {
      console.error("保存数据区域失败:", error);
      message.error((error as Error)?.message || "保存失败");
    }
  };

  // 添加数据成功回调
  const handleAddDataSuccess = async (selectedData: any[]) => {
    try {
      console.log("添加的数据:", selectedData);
      
      if (!selectedTreeKey) {
        message.error("请先选择数据集");
        return;
      }

      // 构造请求参数
      const files = selectedData.map(item => ({
        data_type: item.data_type, // 科学数据类型
        product_id: item.product_id
      }));

      const params = {
        planet_id: planetId,
        tree_uuid: selectedTreeKey,
        files: files
      };

      // 调用接口添加数据
      const response = await createGISDataAreaFile(params);
      
      if (response.code === 200) {
        message.success(`成功添加 ${selectedData.length} 条数据`);
        setAddDataModalVisible(false);
        // 刷新文件列表
        fetchDataAreas(current, pageSize);
      } else {
        message.error(response.msg || "添加数据失败");
      }
    } catch (error) {
      console.error("添加数据失败:", error);
      message.error((error as Error)?.message || "添加数据失败");
    }
  };

  // 全部添加回调
  const handleAddAll = async (filterParams: any) => {
    try {
      if (!selectedTreeKey) {
        message.error("请先选择数据集");
        return;
      }

      // 构造全部添加参数，直接使用自己的planetId
      const params = {
        planet_id: planetId,  // 直接使用自己的planetId
        tree_uuid: selectedTreeKey,
        ...filterParams
      };

      // 调用全部添加接口
      const response = await createGISDataAreaFileAll(params);
      
      if (response.code === 200) {
        message.success("全部添加成功");
        setAddDataModalVisible(false);
        // 刷新文件列表
        fetchDataAreas(current, pageSize);
      } else {
        message.error(response.msg || "全部添加失败");
      }
    } catch (error) {
      console.error("全部添加失败:", error);
      message.error((error as Error)?.message || "全部添加失败");
    }
  };

  // 表格选择配置
  const dataAreaRowSelection = {
    selectedRowKeys: selectedDataAreaKeys,
    columnWidth: 50,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedDataAreaKeys(newSelectedRowKeys);
    },
  };

  // 数据区域表格列定义
  const dataAreaColumns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      width: 80,
      ellipsis: true,
    },
    {
      title: "文件名",
      dataIndex: "file_name",
      key: "file_name",
      width: 200,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "任务",
      dataIndex: "task",
      key: "task",
      width: 120,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "载荷",
      dataIndex: "dm_zhname",
      key: "dm_zhname",
      width: 120,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "区域名称",
      dataIndex: "area_name",
      key: "area_name",
      width: 150,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "数据等级",
      dataIndex: "data_level",
      key: "data_level",
      width: 120,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "文件大小",
      dataIndex: "data_size",
      key: "data_size",
      width: 120,
      ellipsis: true,
      render: (text: any) => {
        if (text === undefined || text === null || text === "") return "-";
        // 格式化文件大小
        const size = Number(text);
        if (size < 1024) return `${size} B`;
        if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
        if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(2)} MB`;
        return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
      },
    },
    {
      title: "左上点经纬度",
      key: "left_coordinates",
      width: 150,
      ellipsis: true,
      render: (_: any, record: GISDataAreaFileItem) => {
        const lat = record.left_latitude;
        const lng = record.left_longitude;
        if (lat === undefined || lat === null || lng === undefined || lng === null) {
          return "-";
        }
        return `${lat}, ${lng}`;
      },
    },
    {
      title: "右下点经纬度",
      key: "right_coordinates",
      width: 150,
      ellipsis: true,
      render: (_: any, record: GISDataAreaFileItem) => {
        const lat = record.right_latitude;
        const lng = record.right_longitude;
        if (lat === undefined || lat === null || lng === undefined || lng === null) {
          return "-";
        }
        return `${lat}, ${lng}`;
      },
    },
    {
      title: "文件路径",
      dataIndex: "file_path",
      key: "file_path",
      width: 200,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "上传时间",
      dataIndex: "create_time",
      key: "create_time",
      width: 180,
      ellipsis: true,
      render: (text: any) => (text === undefined || text === null || text === "" ? "-" : text),
    },
    {
      title: "操作",
      key: "action",
      width: 200,
      fixed: "right" as const,
      align: "center" as const,
      render: (_: any, record: GISDataAreaFileItem) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEditDataArea(record)}>
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteDataArea(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 计算表格滚动高度（根据容器高度自适应）
  const calculateTableScrollHeight = () => {
    // 仅在显示数据内容时计算
    if (!tableContainerRef.current) return;
    const container = tableContainerRef.current;
    const containerHeight = container.clientHeight; // 容器可用高度
    const tableHeaderHeight = 90; // 估算表头高度
    const scrollHeight = Math.max(containerHeight - tableHeaderHeight, 100);
    setTableScrollY(scrollHeight);

    // 直接限制表体高度，避免出现双滚动条
    const tableBody = container.querySelector(".ant-table-body") as HTMLElement | null;
    if (tableBody) {
      tableBody.style.height = `${scrollHeight}px`;
      tableBody.style.maxHeight = `${scrollHeight}px`;
    }
  };

  useEffect(() => {
    // 延迟以确保DOM渲染完成
    const timer = setTimeout(() => {
      calculateTableScrollHeight();
    }, 100);

    const onResize = () => calculateTableScrollHeight();
    window.addEventListener("resize", onResize);
    return () => {
      clearTimeout(timer);
      window.removeEventListener("resize", onResize);
    };
  }, [showDataContent]);

  return (
    <div
      style={{
        display: "flex",
        width: "100%",
        minWidth: "1200px",
        height: "calc(100vh - 277px)", // 减去面包屑和padding的高度
        overflow: "hidden",
      }}
    >
      {/* 左侧树形结构 */}
      <div
        style={{
          width: "350px",
          flexShrink: 0,
          marginRight: "16px",
          height: "100%",
          display: "flex",
          flexDirection: "column",
        }}
      >
        <div
          className="data-area-tree-container"
          style={{
            height: "100%",
            display: "flex",
            flexDirection: "column",
          }}
        >
          <div style={{ display: "flex", gap: 8, marginBottom: 12, flexShrink: 0 }}>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddTask}>
              添加探测任务
            </Button>
          </div>

          <div style={{ flex: 1, overflow: "auto" }}>
            <Spin spinning={treeLoading}>
              {treeData.length === 0 ? (
                <Empty description="暂无数据" />
              ) : (
                <Tree
                  treeData={treeData}
                  expandedKeys={expandedKeys}
                  onExpand={setExpandedKeys}
                  selectedKeys={selectedTreeKey ? [selectedTreeKey] : []}
                  onSelect={(keys: React.Key[]) => {
                    const selectedKey = keys[0] as string;
                    
                    // 如果点击的是第一级节点（任务节点），用于切换展开/收起
                    const isTaskNode = treeData.some((task) => task.key === selectedKey);
                    if (isTaskNode) {
                      const isExpanded = expandedKeys.includes(selectedKey);
                      if (isExpanded) {
                        // 如果已展开，则收起
                        setExpandedKeys(expandedKeys.filter(key => key !== selectedKey));
                      } else {
                        // 如果未展开，则展开
                        setExpandedKeys([...expandedKeys, selectedKey]);
                      }
                      return; // 不设置选中状态
                    }
                    
                    // 如果点击的是第二级节点（数据集），设置选中状态
                    setSelectedTreeKey(selectedKey);
                    setTreeUuid(selectedKey);
                    // 检查选中的节点是否是数据集（叶子节点）
                    const isDataSet = treeData.some((task) =>
                      task.children?.some((dataSet) => dataSet.key === selectedKey)
                    );
                    setShowDataContent(isDataSet);

                    // 如果选择了数据集节点，重置分页
                    if (isDataSet) {
                      setCurrent(1);
                    }
                  }}
                  blockNode={true}
                  titleRender={(nodeData: TreeNode) => {
                    const isTask = !nodeData.isLeaf;
                    return (
                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: 6,
                        }}
                      >
                        <span
                          style={{
                            whiteSpace: "nowrap",
                            overflow: "hidden",
                            textOverflow: "ellipsis",
                          }}
                        >
                          {nodeData.title}
                        </span>
                        <Space size={0} style={{ marginLeft: 8 }}>
                          <Button
                            type="text"
                            size="small"
                            icon={<EditOutlined />}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleEditNode(nodeData);
                            }}
                          />
                          {isTask && (
                            <Button
                              type="text"
                              size="small"
                              icon={<FolderAddOutlined />}
                              onClick={(e) => {
                                e.stopPropagation();
                                handleAddDataSet(nodeData.key);
                              }}
                            />
                          )}
                          <Button
                            type="text"
                            size="small"
                            danger
                            icon={<DeleteOutlined />}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleDeleteNode(nodeData.key);
                            }}
                          />
                        </Space>
                      </div>
                    );
                  }}
                />
              )}
            </Spin>
          </div>
        </div>
      </div>

      {/* 右侧主内容区 */}
      <div
        style={{
          flex: 1,
          height: "100%",
          display: "flex",
          flexDirection: "column",
          overflow: "hidden",
        }}
      >
        {selectedTreeKey ? (
          showDataContent ? (
            <div
              style={{
                height: "100%",
                display: "flex",
                flexDirection: "column",
              }}
            >
              {/* 筛选表单 */}
              <div style={{ flexShrink: 0 }}>
                <Form
                  form={dataAreaFilterForm}
                  layout="inline"
                  className="filter-form"
                  onFinish={onDataAreaFilterFinish}
                  labelCol={{ style: { width: 70 } }}
                >
                  <Form.Item name="file_name" label="文件名" style={{ width: 250 }}>
                    <Input placeholder="请输入文件名搜索" />
                  </Form.Item>
                  <Form.Item name="dm_zhname" label="载荷" style={{ width: 250 }}>
                    <Input placeholder="请输入载荷搜索" />
                  </Form.Item>
                  <Form.Item name="data_level" label="数据等级" style={{ width: 250 }}>
                    <Input placeholder="请输入数据等级搜索" />
                  </Form.Item>
                  <Form.Item name="create_time_range" label="上传时间" style={{ width: 360 }}>
                    <RangePicker 
                      style={{ width: 280 }} 
                      placeholder={['开始时间', '结束时间']}
                      showTime={{ format: 'HH:mm:ss' }}
                      format="YYYY-MM-DD HH:mm:ss"
                    />
                  </Form.Item>
                  <Form.Item style={{ paddingLeft: 40 }}>
                    <Space>
                      <Button type="primary" htmlType="submit">
                        筛选
                      </Button>
                      <Button
                        htmlType="button"
                        onClick={() => {
                          dataAreaFilterForm.resetFields();
                          fetchDataAreas(1, pageSize);
                        }}
                      >
                        清除
                      </Button>
                    </Space>
                  </Form.Item>
                </Form>
              </div>

              {/* 操作按钮 */}
              <div
                style={{
                  marginBottom: 16,
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                  flexShrink: 0,
                }}
              >
                <div>
                  <Button
                    type="primary"
                    danger
                    onClick={handleBatchDeleteDataArea}
                    loading={batchDeleteLoading}
                    disabled={selectedDataAreaKeys.length === 0}
                  >
                    批量删除
                  </Button>
                </div>

                <Space>
                  <Button onClick={handleExport} disabled={!selectedTreeKey}>
                    导出
                  </Button>
                  <Button onClick={() => setImportVisible(true)} disabled={!selectedTreeKey}>
                    导入
                  </Button>
                  <Button type="primary" icon={<PlusOutlined />} onClick={() => setAddDataModalVisible(true)}>
                    添加数据
                  </Button>
                </Space>
              </div>

              {/* 数据表格 */}
              <div style={{ flex: 1, overflow: "hidden" }}>
                <div className="pds-table-container" style={{ height: "100%" }} ref={tableContainerRef}>
                  <Table
                    rowSelection={dataAreaRowSelection}
                    columns={dataAreaColumns}
                    dataSource={dataAreas}
                    rowKey="id"
                    loading={dataAreaLoading}
                    pagination={{
                      current,
                      pageSize,
                      total,
                      showSizeChanger: true,
                      pageSizeOptions: ["10", "20", "50"],
                      onChange: (page, size) => {
                        setCurrent(page);
                        setPageSize(size);
                      },
                      showTotal: (total) => `共 ${total} 条`,
                    }}
                    scroll={{ y: tableScrollY, x: "max-content" }}
                    bordered
                    size="small"
                    onChange={handleDataAreaTableChange}
                  />
                </div>
              </div>
            </div>
          ) : (
            <div
              style={{
                height: "100%",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                fontSize: 18,
                color: "#999",
                background: "white",
              }}
            >
              请选择数据集节点查看数据
            </div>
          )
        ) : (
          <div
            style={{
              height: "100%",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: 18,
              color: "#999",
              background: "white",
            }}
          >
            请先选择左侧树节点
          </div>
        )}
      </div>

      {/* 编辑数据区域弹窗 */}
      <Modal
        title="编辑文件坐标和区域名称"
        open={dataAreaModalVisible}
        onOk={handleSaveDataArea}
        onCancel={() => setDataAreaModalVisible(false)}
        width={800}
        okText="保存"
        cancelText="取消"
      >
        <Form form={dataAreaForm} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item
            name="area_name"
            label="区域名称"
            rules={[{ message: "请输入区域名称" }]}
          >
            <Input placeholder="请输入区域名称" />
          </Form.Item>
          <div style={{ display: "flex", gap: 16 }}>
            <div style={{ flex: 1 }}>
              <Form.Item
                name="left_latitude"
                label="左上点纬度"
                rules={[{ required: true, message: "请输入左上点纬度" }]}
              >
                <InputNumber placeholder="请输入左上点纬度" style={{ width: "100%" }} />
              </Form.Item>
              <Form.Item
                name="left_longitude"
                label="左上点经度"
                rules={[{ required: true, message: "请输入左上点经度" }]}
              >
                <InputNumber placeholder="请输入左上点经度" style={{ width: "100%" }} />
              </Form.Item>
            </div>
            <div style={{ flex: 1 }}>
              <Form.Item
                name="right_latitude"
                label="右下点纬度"
                rules={[{ required: true, message: "请输入右下点纬度" }]}
              >
                <InputNumber placeholder="请输入右下点纬度" style={{ width: "100%" }} />
              </Form.Item>
              <Form.Item
                name="right_longitude"
                label="右下点经度"
                rules={[{ required: true, message: "请输入右下点经度" }]}
              >
                <InputNumber placeholder="请输入右下点经度" style={{ width: "100%" }} />
              </Form.Item>
            </div>
          </div>
        </Form>
      </Modal>

      {/* 添加数据弹窗 */}
      <AddDataPickerModal
        open={addDataModalVisible}
        onCancel={() => setAddDataModalVisible(false)}
        onOk={handleAddDataSuccess}
        onAddAll={handleAddAll}
      />

      {/* 批量导入弹窗 */}
      <DataAreaBatchUploadModal
        visible={importVisible}
        onCancel={() => setImportVisible(false)}
        planetId={planetId}
        treeUuid={selectedTreeKey || ""}
        onSuccess={() => {
          // 刷新当前文件列表
          fetchDataAreas(current, pageSize);
        }}
      />

      {/* 编辑节点名称弹窗 */}
      <Modal
        title={editingNode?.isLeaf ? "编辑数据集名称" : "编辑探测任务名称"}
        open={editNodeModalVisible}
        onOk={handleSaveNodeEdit}
        onCancel={() => {
          setEditNodeModalVisible(false);
          setEditingNode(null);
          setAddingToParentKey(null);
          editNodeForm.resetFields();
        }}
        width={400}
        okText="保存"
        cancelText="取消"
      >
        <Form form={editNodeForm} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item
            name="title"
            label={editingNode?.isLeaf ? "数据集名称" : "探测任务名称"}
            rules={[{ required: true, message: `请输入${editingNode?.isLeaf ? "数据集名称" : "探测任务名称"}` }]}
          >
            <Input placeholder={`请输入${editingNode?.isLeaf ? "数据集名称" : "探测任务名称"}`} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DataAreaManagement;
